package com.egc.essm.util;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.collections.map.CaseInsensitiveMap;
import org.apache.commons.lang.StringUtils;

/**
 * 
 * 
 * @author  yuhanyang
 * @version  [版本号, 2017年11月1日]
 * @see  [相关类/方法]
 * @since  [产品/模块版本]
 */
public class MapUtil
{
    private static Pattern KVSTRING_PATTERN = Pattern.compile("((\\w+=[^=]+)(?=&|\\z))");
    
    private static Pattern KEYVALUE_PATTERN = Pattern.compile("(\\w+)=(.+)");
    
    public static String getvalue(String key, Map map, String defaultVal)
    {
        if (map == null || key == null || "".equals(key))
        {
            return defaultVal;
        }
        
        String value = (String)map.get(key);
        return value == null || "".equals(value) ? defaultVal : value;
    }
    
    public static String getvalue(String key, Map map)
    {
        return getvalue(key, map, "");
    }
    
    /**
     * 
     * key=value&key=value的字符串转换为Map(map中key全大写)
     * 
     * @param string
     * @return
     * @see [类、类#方法、类#成员]
     */
    public static Map<String, String> kvString2upperCaseMap(String string)
    {
        return kvString2Map(string, true);
    }
    
    /**
     * 
     * key=value&key=value的字符串转换为Map
     * 
     * @param string
     * @return
     * @see [类、类#方法、类#成员]
     */
    public static Map<String, String> kvString2Map(String string)
    {
        return kvString2Map(string, false);
    }
    
    /**
     * key=value&key=value的字符串转换为Map
     * 
     * 
     * @param string
     * @param upperCase key是否大写
     * @return
     * @see [类、类#方法、类#成员]
     */
    public static Map<String, String> kvString2Map(String string, boolean upperCase)
    {
        Map<String, String> params = new HashMap<String, String>(16);
        Matcher matcher = KVSTRING_PATTERN.matcher(string);
        
        while (matcher.find())
        {
            Matcher detailMatcher = KEYVALUE_PATTERN.matcher(matcher.group(1));
            if (detailMatcher.find())
            {
                if (upperCase)
                {
                    params.put(detailMatcher.group(1).toUpperCase(Locale.getDefault()), detailMatcher.group(2));
                }
                else
                {
                    params.put(detailMatcher.group(1), detailMatcher.group(2));
                }
            }
        }
        
        return params;
    }
    
    /**
     * 
     * Map转换为key=value&key=value的字符串
     * 
     * @param string
     * @return
     * @see [类、类#方法、类#成员]
     */
    public static String map2KVString(Map<String, String> params)
    {
        StringBuffer buffer = new StringBuffer();
        int index = 1;
        for (String key : params.keySet())
        {
            String value = params.get(key);
            
            if (StringUtils.isNotEmpty(value))
            {
                buffer.append(key).append("=").append(value);
            }
            
            if (index < params.size())
            {
                buffer.append("&");
            }
            
            index++;
        }
        
        return buffer.toString();
    }
    
    /**
     * Map转成String
     * 
     * @param map
     * @return
     * @see [类、类#方法、类#成员]
     */
    public static String mapToString(Map<String, String> map)
    {
        StringBuffer buf = new StringBuffer();
        Iterator<Entry<String, String>> iterator = map.entrySet().iterator();
        while (iterator.hasNext())
        {
            Entry<String, String> entry = iterator.next();
            String key = entry.getKey();
            String value = entry.getValue();
            buf.append(key).append(":").append(value).append("\n");
        }
        return buf.toString();
    }
    
    /**
     * map转业务类
     * 
     * @param map
     * @param beanClass
     * @return
     * @throws Exception
     */
    public static Object mapToObject(Map<String, String> map, Class<?> beanClass) throws Exception
    {
        if (map == null)
        {
            return null;
        }
        
        CaseInsensitiveMap myMap = new CaseInsensitiveMap();
        
        for (Map.Entry<String, String> entry : map.entrySet())
        {
            myMap.put(entry.getKey(), entry.getValue());
        }
        
        Object obj = beanClass.newInstance();
        
        Field[] fields = obj.getClass().getDeclaredFields();
        for (Field field : fields)
        {
            int mod = field.getModifiers();
            if (Modifier.isStatic(mod) || Modifier.isFinal(mod))
            {
                continue;
            }
            
            field.setAccessible(true);
            field.set(obj, myMap.get(field.getName()));
        }
        
        return obj;
    }
}
